extends KinematicBody2D
class_name KObj

var knightAniIndex : float = 10;
var knightAniNum : int = 20;
# 1 超右 -1 超左
var knightFace : int = 1; 

var x:float = 200;
var y:float = 200;
# 速度标量
var speed = 200;
# 速度向量
var velocity = Vector2();
var knight:Sprite;

func _init():
    # 创建碰撞体
    self.position = Vector2(x,y)

    # 外观
    knight = Sprite.new();
    knight.texture = load("res://knight.png")
    knight.hframes = 10;
    knight.vframes = 2;

    # 默认frame
    knight.frame = floor(knightAniIndex);
    self.add_child(knight);

    # 实际大小
    var h = knight.texture.get_height() / knight.vframes;
    var w = knight.texture.get_width() / knight.hframes;

    # 碰撞盒
    var rect = RectangleShape2D.new();
    rect.extents = Vector2(w,h);
    var oid = self.create_shape_owner(self);
    self.shape_owner_add_shape(oid,rect);
    print("radius",rect.extents);

func _physics_process(delta):
    # 生成速度
    handle_input();
    
    # 移动并检测碰撞
    var col:KinematicCollision2D = move_and_collide(velocity * delta)
    if col:
        print("col",col);

func handle_input():
    velocity = Vector2()
    var isMove = false
    if Input.is_action_pressed('ui_right'):
        isMove = true
        knightFace = 1
        velocity.x += 1
    if Input.is_action_pressed('ui_left'):
        isMove = true
        knightFace = -1
        velocity.x -= 1
    velocity = velocity.normalized() * speed
    
    if(isMove):
        if(floor(knightAniIndex) == knightAniNum -1):
            knightAniIndex = 10
        else:
            knightAniIndex = knightAniIndex + 0.3
    
        knight.frame = floor(knightAniIndex);
        knight.scale = Vector2(knightFace,1);
    
    pass;